<template>
  <div class="contentView" v-loading="formLoading" :style="`height:${contentHeight}px`">
    <div class="routeHeader mb-5px">
      <!-- <el-button
        type="primary"
        @click="submitForm"
        :loading="formLoading"
        v-hasPermi="['produce:course-test-machine:save']"
      >
        保 存
      </el-button> -->
      <el-button @click="goBack">关 闭</el-button>
    </div>
    <p class="baseTitle">工单信息</p>
    <ContentWrap>
      <div class="disFlex">
        <div class="cell">
          <span>工单号：</span>
          <span>{{ formData.workTaskNumber }}</span>
        </div>
        <div class="cell">
          <span>产品编号：</span>
          <span>{{ formData.productNumber }}</span>
        </div>
        <div class="cell">
          <span>产品名称：</span>
          <span>{{ formData.productName }}</span>
        </div>
      </div>
      <div class="disFlex bg">
        <div class="cell">
          <span>部件编号：</span>
          <span>{{ formData.partNumber }}</span>
        </div>
        <div class="cell">
          <span>部件名称：</span>
          <span>{{ formData.partName }}</span>
        </div>
        <div class="cell">
          <span>图纸图号：</span>
          <span>{{ formData.drawingNumber }}</span>
        </div>
      </div>
      <div class="disFlex">
        <div class="cell">
          <span>计划数量：</span>
          <span>{{ formData.planQuantity }}</span>
        </div>
        <div class="cell">
          <span>完工数量：</span>
          <span>{{ formData.completeQuantity }}</span>
        </div>
        <div class="cell">
          <span>差异数量：</span>
          <span>{{ formData.differenceQuantity }}</span>
        </div>
      </div>
    </ContentWrap>
    <p class="baseTitle mt-10px">生产任务</p>
    <el-table
      ref="singleTableRef"
      :data="productionTasksList"
      style="width: 100%"
      border
      :header-cell-style="headFirst"
      default-expand-all
      row-key="id"
    >
      <el-table-column type="index" fixed="left" label="序号" width="80" align="center" />
      <template v-for="(item, index) in productionTasksTitle" :key="index">
        <el-table-column
          :prop="item.val"
          :label="item.label"
          :min-width="item.width"
          :align="item.val == 'processPrice' ? 'right' : 'left'"
          :header-align="item.val == 'processPrice' ? 'right' : 'left'"
        >
          <template #default="scope">
            <!-- 处理报工 -->
            <template v-if="item.val == 'reportQuantity'">
              <el-input-number
                controls-position="right"
                :min="0"
                v-model="scope.row[item.val]"
                :disabled="[20, 40].includes(scope.row.dictStatus)"
                v-if="
                  scope.row.dictReportWay === 10 ||
                  (scope.row.dictReportWay === 20 && scope.row.isChild)
                "
              />
              <span v-else>{{ scope.row[item.val] }}</span>
            </template>
            <dict-tag v-else-if="item.val === 'dictProcessName'" type="craft_process_name" :value="scope.row.dictProcessName" />
            <!-- 处理进度下的展示 -->
            <template
              v-else-if="
                ['planQuantity', 'completeQuantity', 'differenceQuantity'].includes(item.val)
              "
            >
              <!-- 进度 -->
              <template v-if="formData.dictReportWay == 20 && scope.row.isChild">
                {{ formatNum(scope.row[item.val]) }}
              </template>
              <template v-else> {{ scope.row[item.val] }} </template>
            </template>
            <template v-else-if="item.label.includes('图纸图号')">
              <el-button type="primary" link @click="jumpPdfFile(scope.row.drawingNumber)">{{
                scope.row.drawingNumber
              }}</el-button>
            </template>
            <template v-else>{{ scope.row[item.val] }}</template>
          </template>
        </el-table-column>
      </template>

      <el-table-column label="操作" min-width="390" align="left" header-align="left" fixed="right">
        <template #default="scope">
          <el-button
            @click="reportingWork(scope.row)"
            type="primary"
            size="small"
            link
            v-if="
              (scope.row.dictReportWay === 10 ||
                (scope.row.dictReportWay === 20 && scope.row.isChild)) &&
              ![20, 40].includes(scope.row.dictStatus)
            "
            v-hasPermi="['produce:course-test-machine:report']"
          >
            报工
          </el-button>
          <template
          v-if="
              scope.row.dictReportWay === 10 || (scope.row.dictReportWay && scope.row.hasChild)
            "
          >
            <el-button
              @click="showDrawingNumber(scope.row.drawingNumber)"
              type="primary"
              size="small"
              link
              v-hasPermi="['produce:course-test-machine:drawing']"
            >
              查看图纸
            </el-button>
            <el-button
              @click="showWorkingInstruction(scope.row)"
              type="primary"
              size="small"
              link
              v-hasPermi="['produce:course-test-machine:workingInstruction']"
            >
              查看作业指导书
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="openMaterial(scope.row.productNumber,scope.row.partNumber)"
              link
              v-hasPermi="['produce:course-test-machine:bom']"
            >
              查看物料清单
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 报工 -->
    <reportingWorkView ref="reportingWorkRef" @refresh="refreshData" />
    <!-- 查看作业指导书 -->
    <workingInstruction ref="workingInstructionRef" />
    <!-- 查看图纸 -->
    <drawingNumber ref="drawingNumberRef" />
    <!-- 查看物料清单 -->
    <material
      v-show="showMaterial"
      ref="materialRef"
      class="material"
      :style="`height:${contentHeight}px`"
      @closeView="showMaterial = false"
    />
  </div>
</template>
<script setup lang="ts">
  import { jumpPdfFile } from '@/utils/formCreate'
  import * as CourseTestMachineApi from '@/api/produce/processManagement/courseTestMachine'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  //报工
  import reportingWorkView from '../components/reportingWork.vue'
  import request from '@/config/axios'
  import material from '../components/material.vue'
  //查看作业指导书
  import workingInstruction from '../components/workingInstruction.vue'
  //查看图纸
  import drawingNumber from '../components/drawingNumber.vue'
  /**查看作业指导书 */
  const workingInstructionRef = ref()
  const showWorkingInstruction = (data) => {
    workingInstructionRef.value.open(data)
  }
  //查看图纸
  const drawingNumberRef = ref()
  const showDrawingNumber = (drawingNumber) => {
    drawingNumberRef.value.open(drawingNumber)
  }
  // const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗

  const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
  const formData = ref({})

  /**百分比转换 */
  const formatNum = (num: number) => {
    return `${parseFloat(num * 100)}%`
  }

  /**报工 */
  const reportingWorkRef = ref()
  const reportingWork = async (row: object) => {
    if (!row['processPrice']) {
      const res = await getProcessingUnitPrice({
        productNumber: row['productNumber'],
        partNumber: row['partNumber'],
        dictProcessName: row['dictProcessName']
      })
      if (res.code == 1100000113) {
        message.notifyError(res.msg)
        return
      }
      row.processPrice = res.unitPrice
    }
    if (row['dictReportWay'] === 10) {
      if (parseFloat(row['reportQuantity']) > parseFloat(row['differenceQuantity'])) {
        message.notifyError('报工数量不能大于差异数量')
        return
      }
      if (!row['reportQuantity']) {
        message.notifyError('请输入报工数量')
        return
      }
    } else {
      if (parseFloat(row['reportQuantity']) / 100 > parseFloat(row['differenceQuantity'])) {
        message.notifyError('报工进度不能大于差异进度')
        return
      }
      if (!row['reportQuantity']) {
        message.notifyError('请输入报工进度')
        return
      }
    }
    reportingWorkRef.value.open(row, 'produce/course-test-machine/workTime', formData.value.planQuantity)
  }

  /**获取加工单价 */
  const getProcessingUnitPrice = async (params: object) => {
    const res = await request.get({ url: '/config/wage-quotations-confirmed-task/getPrice', params })
    return res
  }
  // 打开物料清单
  const showMaterial = ref(false)
  const materialRef = ref()
  const openMaterial = (productNumber: string,partNumber: string) => {
    showMaterial.value = true
    materialRef.value!.getData(productNumber,partNumber)
  }

  /**返回 */
  const tagsViewStore = useTagsViewStore()
  const route = useRouter() // 路由
  const goBack = async () => {
    //获取当前路由并删除tagView
    tagsViewStore.delView(route.currentRoute.value)
    //跳转列表页
    route.push({
      path: '/produce/produce/processManagement/courseTestMachine'
    })
  }
  /** 提交表单 */
  // const submitForm = async () => {
  //   formLoading.value = true
  //   const data = JSON.parse(JSON.stringify(formData.value))
  //   try {
  //     await CourseTestMachineApi.updateCourseTestMachine(data)
  //     message.success(t('common.updateSuccess'))
  //   } finally {
  //     formLoading.value = false
  //   }
  // }

  //生产任务表头
  const productionTasksTitle = ref([
    {
      label: '工序名称',
      val: 'dictProcessName',
      width: 250
    },
    {
      label: '细部工序',
      val: 'subProcessName',
      width: 200
    },
    {
      label: '工单号/任务单号',
      val: 'workTaskNumber',
      width: 200
    },
    {
      label: '产品编号',
      val: 'productNumber',
      width: 200
    },
    {
      label: '产品名称',
      val: 'productName',
      width: 200
    },
    {
      label: '产品规格',
      val: 'productStandard',
      width: 200
    },
    {
      label: '订单数量',
      val: 'orderQuantity',
      width: 200
    },
    {
      label: '编号',
      val: 'code',
      width: 200
    },
    {
      label: '部件编号',
      val: 'partNumber',
      width: 200
    },
    {
      label: '部件名称',
      val: 'partName',
      width: 200
    },
    {
      label: '图纸图号',
      val: 'drawingNumber',
      width: 200
    },
    {
      label: '部件规格',
      val: 'partSpecification',
      width: 200
    },
    {
      label: '单位',
      val: 'partUnit',
      width: 200
    },
    {
      label: '计划数量',
      val: 'planQuantity',
      width: 200
    },
    {
      label: '报工数量/报工进度',
      val: 'reportQuantity',
      width: 200
    },
    {
      label: '完工数量',
      val: 'completeQuantity',
      width: 200
    },
    {
      label: '差异数量',
      val: 'differenceQuantity',
      width: 200
    },
    {
      label: '加工单价',
      val: 'processPrice',
      width: 200
    },
    {
      label: '生产班组',
      val: 'productionTeam',
      width: 200
    },
    {
      label: '设备名称',
      val: 'deviceName',
      width: 200
    },
    {
      label: '设备编码',
      val: 'deviceCode',
      width: 200
    },
    {
      label: '作业者',
      val: 'operator',
      width: 200
    }
  ])
  // 获得id
  const { query } = useRoute() // 路由的查询
  const contentHeight = ref(0)
  const productionTasksList = ref([])
  const refreshData = async () => {
    formLoading.value = true
    if (query.id) {
      formData.value = await CourseTestMachineApi.getCourseTestMachine(query.id)
      if (formData.value.children.length) {
        formData.value.hasChild = true
      }
      formData.value.children.map((item) => {
        item.isChild = true
        return item
      })
      formData.value.parentIndex = 1
      productionTasksList.value = [formData.value]
      console.log(productionTasksList.value, 'productionTasksList')
      contentHeight.value = document.body.clientHeight - 127
    }
    formLoading.value = false
  }

  // 合并编号
  const headFirst = ({ rowIndex }) => {
    if (rowIndex === 1) {
      return { display: 'none' }
    }
  }
  onMounted(() => {
    refreshData()
  })
</script>
<style lang="scss" scoped>
  .disFlex {
    display: flex;
  }

  .contentView {
    padding: 10px;
    background: #fff;
    position: relative;

    .material {
      width: 100%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 99;
    }
  }

  .cell {
    width: 28%;
    height: 60px;
    line-height: 60px;
    padding-left: 10px;
    box-sizing: border-box;
  }

  .bg {
    background-color: #f0f1f5;
  }

  .tableView {
    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
      cursor: default;

      .el-input__inner {
        cursor: default !important;
        text-align: center;
      }
    }
  }
</style>
